package com.xbongbong.workflow.service.strategy.node.impl;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.config.enums.WorkflowTaskLogStatusEnum;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.domain.entity.ext.OptionalRangeEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.ApproverDeduplicationEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.NodeTypeEnum;
import com.xbongbong.paas.enums.TaskTypeEnum;
import com.xbongbong.paas.exception.WorkflowException;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.help.WorkflowHelp;
import com.xbongbong.paas.help.WorkflowRecordLogHelp;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.service.WorkflowApprovalOperate;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.WorkflowUtil;
import com.xbongbong.parent.help.PushMessageHelp;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.message.service.MessageService;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.SignTypeEnum;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.workflow.domain.entity.WorkflowEntity;
import com.xbongbong.workflow.domain.entity.WorkflowNodeEntity;
import com.xbongbong.workflow.domain.entity.WorkflowTaskEntity;
import com.xbongbong.workflow.domain.entity.WorkflowTaskNodeEntity;
import com.xbongbong.workflow.enums.WorkflowNodeTypeEnum;
import com.xbongbong.workflow.model.WorkflowModel;
import com.xbongbong.workflow.model.WorkflowNodeModel;
import com.xbongbong.workflow.model.WorkflowTaskLogItemModel;
import com.xbongbong.workflow.model.WorkflowTaskModel;
import com.xbongbong.workflow.model.WorkflowTaskNodeModel;
import com.xbongbong.workflow.model.WorkflowTransferDataModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.User;
import com.xbongbong.workflow.pojo.WorkflowCreateTaskNodePojo;
import com.xbongbong.workflow.pojo.WorkflowProcessResultPojo;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.pojo.bo.WorkflowDeDuplicationBo;
import com.xbongbong.workflow.pojo.bo.WorkflowNoApproverBo;
import com.xbongbong.workflow.pojo.changerecord.ChangeRecordMidPojo;
import com.xbongbong.workflow.pojo.nodes.ApprovalNode;
import com.xbongbong.workflow.pojo.nodes.WorkflowTitlePojo;
import com.xbongbong.workflow.service.strategy.node.AbstractWorkflowApprovalStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 流程节点
 * @author 魏荣杰
 */
@Service
@Slf4j
public class WorkflowNodeApproveStrategy extends AbstractWorkflowApprovalStrategy {

    private static final Logger LOGGER = LoggerFactory.getLogger(WorkflowNodeApproveStrategy.class);

    @Resource
    private WorkflowTaskNodeModel workflowTaskNodeModel;
    @Resource
    private WorkflowModel workflowModel;
    @Resource
    private WorkflowTaskModel workflowTaskModel;
    @Resource
    private UserModel userModel;
    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private WorkflowNodeModel workflowNodeModel;
    @Resource
    private WorkflowTransferDataModel workflowTransferDataModel;
    @Resource
    private WorkflowTaskLogItemModel workflowTaskLogItemModel;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private PushMessageHelp pushMessageHelp;
    @Resource
    private MessageService messageService;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private WorkflowHelp workflowHelp;
    @Resource
    private WorkflowApprovalOperate workflowApprovalOperate;
    @Resource
    private WorkflowRecordLogHelp workflowRecordLogHelp;

    @Override
    public String type() {
        return WorkflowNodeTypeEnum.APPROVE_NODE.getName();
    }

    @Override
    public void before(WorkflowTransferPOJO workflowTransferPOJO) {
        super.before(workflowTransferPOJO);
    }

    @Override
    public WorkflowProcessResultPojo process(WorkflowTransferPOJO workflowTransferPOJO, WorkflowNodeEntity workflowNodeEntity, Long lastNodeId, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) {
        // 是否需要人员审批介入
        boolean isNeedApproval = true;
        Integer autoPaas = 0;
        // 是否自动通过
        boolean isAutoApproval = false;
        try {
            //用于判断是不是首次进审批
            Long taskId = workflowTransferPOJO.getTaskId();
            // 创建主任务
            WorkflowCreateTaskNodePojo workflowCreateTaskNodePojo = createTask(workflowTransferPOJO, workflowNodeEntity);
            isNeedApproval = workflowCreateTaskNodePojo.getIsNeedApproval();
            log.info("isNeedApproval--" + isNeedApproval );
            // 无需审批人逻辑
            if (isNeedApproval) {
                // 创建任务节点
                WorkflowNoApproverBo workflowNoApproverBo = createTaskNode(workflowTransferPOJO, workflowNodeEntity, lastNodeId);
                autoPaas = workflowNoApproverBo.getAutoPaas();

                log.info("isAutoApproval--" + Objects.equals(autoPaas, 1) );
                Map<String, Object> param = new HashMap<>();
                param.put(ParameterConstant.CORPID, workflowNodeEntity.getCorpid());
                param.put(ParameterConstant.APPID, workflowNodeEntity.getAppId());
                param.put(ParameterConstant.MENUID, workflowNodeEntity.getMenuId());
                param.put(ParameterConstant.FORMID, workflowNodeEntity.getFormId());
                param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                param.put("taskId", workflowTransferPOJO.getTaskId());
                param.put("workflowId", workflowNodeEntity.getWorkflowId());
                param.put("taskType", TaskTypeEnum.UNTREATED.getType());
                param.put(ParameterConstant.ORDER_BY_STR, "update_time asc, id asc");
                List<WorkflowTaskNodeEntity> workflowTaskNodeEntities = workflowTaskNodeModel.findEntities(param);
                List<String> userIdIn = new ArrayList<>();
                workflowTaskNodeEntities.forEach(workflowTaskNodeEntity -> userIdIn.add(workflowTaskNodeEntity.getUserId()));
                List<UserEntity> userEntityList = userModel.getByUserIdIn(workflowNodeEntity.getCorpid(), userIdIn, true);
                List<String> userNameList = new ArrayList<>();
                userEntityList.forEach(userEntity -> userNameList.add(userEntity.getName()));
                String waitApproveUserName = StringUtils.join(userNameList, StringConstant.COMMA);
                UserVO userVO = userModel.getUserVO(workflowNodeEntity.getCorpid(), workflowTransferPOJO.getUser().getUserId(), false,false);
                // 创建工作流log节点
                if (Objects.equals(autoPaas, 1)) {
                    // 自动通过
                    logger(workflowTransferPOJO, workflowNodeEntity, WorkflowTaskLogStatusEnum.PASS, new WorkflowException(MessageConstant.WORKFLOW_NODE_PAAS_APPROVE));
                    isAutoApproval = true;
                    //编辑数据的时候需要进行日志记录
                    Integer operate = workflowTransferPOJO.getOperate();
                    if (Objects.isNull(taskId) && Objects.equals(WorkflowOperateEnum.UPDATE.getType(), operate)) {
                        ChangeRecordMidPojo changeRecordMidPojo = workflowRecordLogHelp.getChangeRecordMidPojo(workflowTransferPOJO);
                        changeRecordMidPojo.setOriginalOldData(workflowTransferPOJO.getOldData().getData());
                        changeRecordMidPojo.setOriginalNewData(workflowTransferPOJO.getData().getData());
                        changeRecordMidPojo.setCorpid(workflowNodeEntity.getCorpid());
                        changeRecordMidPojo.setWorkflowTaskId(workflowCreateTaskNodePojo.getTaskId());
                        changeRecordMidPojo.setWorkflowNodeId(workflowCreateTaskNodePojo.getWorkflowNodeId());
                        changeRecordMidPojo.setUserVO(userVO);
                        workflowRecordLogHelp.recordDataChange(changeRecordMidPojo);
                    }
                } else if (Objects.equals(autoPaas, 2)) {
                    logger(workflowTransferPOJO, workflowNodeEntity, WorkflowTaskLogStatusEnum.WAIT, new WorkflowException(MessageConstant.WORKFLOW_NODE_WAIT_APPROVE, waitApproveUserName));
                    // 自动拒绝
                    param.put("taskType", TaskTypeEnum.END.getType());
                    param.put("workflowNodeId", workflowNodeEntity.getId());
                    param.put("pageSize", 1);
                    param.put("start", 0);
                    List<WorkflowTaskNodeEntity> entities = workflowTaskNodeModel.findEntities(param);
                    workflowApprovalOperate.refuse(entities.get(0), true, workflowTransferPOJO, userVO);
                } else {
                    logger(workflowTransferPOJO, workflowNodeEntity, WorkflowTaskLogStatusEnum.WAIT, new WorkflowException(MessageConstant.WORKFLOW_NODE_WAIT_APPROVE, waitApproveUserName));
                    //编辑数据的时候需要进行日志记录
                    Integer operate = workflowTransferPOJO.getOperate();
                    if (Objects.isNull(taskId) && Objects.equals(WorkflowOperateEnum.UPDATE.getType(), operate)) {
                        ChangeRecordMidPojo changeRecordMidPojo = workflowRecordLogHelp.getChangeRecordMidPojo(workflowTransferPOJO);
                        changeRecordMidPojo.setOriginalOldData(workflowTransferPOJO.getOldData().getData());
                        changeRecordMidPojo.setOriginalNewData(workflowTransferPOJO.getData().getData());
                        changeRecordMidPojo.setCorpid(workflowNodeEntity.getCorpid());
                        changeRecordMidPojo.setWorkflowTaskId(workflowCreateTaskNodePojo.getTaskId());
                        changeRecordMidPojo.setWorkflowNodeId(workflowCreateTaskNodePojo.getWorkflowNodeId());
                        changeRecordMidPojo.setUserVO(userVO);
                        workflowRecordLogHelp.recordDataChange(changeRecordMidPojo);
                    }
                }
            } else {
                if (workflowCreateTaskNodePojo.getIsWhitoutApproval()) {
                    // 创建无需审批人日志
                    logger(workflowTransferPOJO, workflowNodeEntity, WorkflowTaskLogStatusEnum.PASS, new WorkflowException(MessageConstant.WORKFLOW_NODE_WITHOUT_APPROVAL));
                } else {
                    // 创建工作流log节点
                    logger(workflowTransferPOJO, workflowNodeEntity, WorkflowTaskLogStatusEnum.PASS, new WorkflowException(MessageConstant.WORKFLOW_NODE_PAAS_APPROVE));
                }

            }

        } catch (WorkflowException e) {
            // 创建工作流错误log节点
            logger(workflowTransferPOJO, workflowNodeEntity, WorkflowTaskLogStatusEnum.FAIL, e);
            log.error("com.xbongbong.workflow.service.strategy.node.impl.WorkflowNodeApproveStrategy.process", e);
        } catch (Exception e) {
            logger(workflowTransferPOJO, workflowNodeEntity, WorkflowTaskLogStatusEnum.FAIL, new WorkflowException(SystemErrorCodeEnum.API_ERROR_100001.getMsg()));
            log.error("com.xbongbong.workflow.service.strategy.node.impl.WorkflowNodeApproveStrategy.process", e);
        }
        return new WorkflowProcessResultPojo(isNeedApproval, isAutoApproval);
    }

    /**
     * Description: 创建审批task任务
     * @param workflowTransferPOJO
     * @param workflowNodeEntity
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2021/5/25 10:56
     * @since
     */
    private WorkflowCreateTaskNodePojo createTask(WorkflowTransferPOJO workflowTransferPOJO, WorkflowNodeEntity workflowNodeEntity) throws WorkflowException {
        Long workflowNodeId = null;
        try {
            Long taskId = workflowTransferPOJO.getTaskId();
            String corpid = workflowNodeEntity.getCorpid();
            // TODO: 2021/5/25 如果是工作流中有审批中的审批其他表，审批初始节点判断，需要更新taskId，现在没有一个工作流审批多个业务
            log.info("create task--------------");

            WorkflowEntity workflowEntity = workflowModel.getByKey(workflowNodeEntity.getWorkflowId(), corpid);
            if (Objects.isNull(workflowEntity)) {
                throw new WorkflowException(MessageConstant.PROCESS_NOT_EXIST);
            }
            // TODO: 2021/5/25 如果其他工作流在使用数据的处理？ 老代码直接报错 数据已在审批中
            Data data = workflowTransferPOJO.getData();
            // TODO: 2021/6/3 现在数据会强制变成审批中数据，逻辑冲突
//            List<PaasFormDataEntityExt> paasFormDataEntityExtList = workflowHelp.getByDataIdList(Collections.singletonList(data.getId()), data.getBusinessType(), data.getSaasMark(), data.getFormId(), corpid);
//            if (Objects.nonNull(paasFormDataEntityExtList) && !paasFormDataEntityExtList.isEmpty()) {
//                PaasFormDataEntityExt paasFormDataEntityExt = paasFormDataEntityExtList.get(0);
//                if (Objects.equals(paasFormDataEntityExt.getFlowStatus(), FlowStatusEnum.IN_APPROVAL.getType()) || Objects.equals(paasFormDataEntityExt.getFlowStatus(), FlowStatusEnum.APPROVAL_PENDING.getType())) {
//                    throw new WorkflowException(MessageConstant.DATA_HAVE_IN_PROCESS);
//                }
//            }

            // 无需审批处理
            User user = workflowTransferPOJO.getUser();
            if (isNoNeedApproval(user, workflowEntity.getRolesWithoutApprove(), corpid)) {
                return new WorkflowCreateTaskNodePojo(false, true);
            }

            // 没有taskId为审批的第一个起始节点
            if (Objects.isNull(taskId)) {
                // TODO: 2021/5/25 编辑还是新建，编辑要判需审批字段？？？触发处理了
                long now = DateTimeUtil.getInt();
                WorkflowTaskEntity workflowTaskEntity = new WorkflowTaskEntity();
                workflowTaskEntity.setCorpid(corpid);
                workflowTaskEntity.setAppId(data.getAppId());
                workflowTaskEntity.setFormId(data.getFormId());
                workflowTaskEntity.setMenuId(data.getMenuId());
                workflowTaskEntity.setWorkflowId(workflowEntity.getId());
                workflowTaskEntity.setDataId(data.getId());
                workflowTaskEntity.setSaasMark(data.getSaasMark());
                workflowTaskEntity.setBusinessType(data.getBusinessType());
                workflowTaskEntity.setFlowStatus(FlowStatusEnum.APPROVAL_PENDING.getType());
                workflowTaskEntity.setCreatorId(user.getUserId());
                workflowTaskEntity.setAddTime(now);
                workflowTaskEntity.setUpdateTime(now);
                workflowTaskEntity.setDel(DelEnum.NORMAL.getDel());
//            workflowTaskEntity.setDingtalkProcessInstanceId();

                Long insert = workflowTaskModel.insert(workflowTaskEntity);
                log.info("create task success taskId --------------" + workflowTaskEntity.getId());
                Runnable runnable = () -> createDingtalkInstance(workflowTransferPOJO, workflowNodeEntity, insert);

                threadPoolBeanConfig.dingtalkTodo().execute(runnable);

                // 绑定审批task
                workflowTransferPOJO.setTaskId(workflowTaskEntity.getId());

                // 创建初始审批记录节点
                WorkflowTaskNodeEntity workflowTaskNodeEntity = new WorkflowTaskNodeEntity();
                workflowTaskNodeEntity.setCorpid(workflowNodeEntity.getCorpid());
                workflowTaskNodeEntity.setAppId(workflowNodeEntity.getAppId());
                workflowTaskNodeEntity.setFormId(workflowNodeEntity.getFormId());
                workflowTaskNodeEntity.setMenuId(workflowNodeEntity.getMenuId());
                workflowTaskNodeEntity.setSaasMark(workflowNodeEntity.getSaasMark());
                workflowTaskNodeEntity.setBusinessType(workflowNodeEntity.getBusinessType());
                workflowTaskNodeEntity.setWorkflowId(workflowNodeEntity.getWorkflowId());
                workflowTaskNodeEntity.setTaskId(workflowTransferPOJO.getTaskId());

                workflowTaskNodeEntity.setUserId(user.getUserId());
                workflowTaskNodeEntity.setDataId(workflowTransferPOJO.getData().getId());
                ApprovalNode approvalNode = JSON.parseObject(workflowNodeEntity.getConfigData(), ApprovalNode.class);
                workflowTaskNodeEntity.setTaskType(TaskTypeEnum.COMMIT.getType());
                workflowTaskNodeEntity.setSignType(approvalNode.getSignType());
                workflowTaskNodeEntity.setNodeType(NodeTypeEnum.START_PROCESS_NODE.getNodeType());
                workflowTaskNodeEntity.setLastNodeId(0L);

                // 初始节点，审批提交节点id用触发节点id
                WorkflowNodeEntity startNode = workflowNodeModel.getByUId(workflowNodeEntity.getWorkflowId(), corpid, "startNode");
                workflowTaskNodeEntity.setWorkflowNodeId(startNode.getId());
                workflowTaskNodeEntity.setOpinion("");
                workflowTaskNodeEntity.setImages("");
                workflowTaskNodeEntity.setAttachment("");
                workflowTaskNodeEntity.setTransferUserId("");
                workflowTaskNodeEntity.setRevokeUserId("");
                workflowTaskNodeEntity.setBackspaceNode(0L);
                workflowTaskNodeEntity.setIsRead(0);
                workflowTaskNodeEntity.setAddTime(now);
                workflowTaskNodeEntity.setUpdateTime(now);
                workflowTaskNodeEntity.setDel(DelEnum.NORMAL.getDel());
                workflowTaskNodeEntity.setSerialNo(data.getData().getString("serialNo") == null ? "" : data.getData().getString("serialNo"));
                // 标题
                Set<Long> workOrder = new HashSet<>();
                Set<Long> others = new HashSet<>();
                Set<Long> workflowNodeIdSet = new HashSet<>();
                List<WorkflowTitlePojo> titles = approvalNode.getTitle();
                // 标题
                WorkflowUtil.getFormIdByTitle(titles, workOrder, others, workflowNodeIdSet);
                //工单的解释
                Map<Long, Map<String, FieldAttrEntity>> workOrderFormExplainMap = proFormHelp.getWorkOrderFormFieldMap(workOrder, workflowNodeEntity.getCorpid());
                //其他表单的解释
                Map<Long, Map<String, FieldAttrEntity>> formExplainMap = proFormHelp.getFormFieldMap(others, workflowNodeEntity.getCorpid());
                // 获取节点数据
                Map<Long, List<PaasFormDataEntityExt>> workflowNodeDataMap = workflowHelp.getWorkflowNodeDataMap(workflowNodeIdSet, workflowTransferPOJO);
                String title;
                //拼接标题
                if (CollectionUtils.isEmpty(titles)) {
                    title = workflowHelp.getDefaultTitle(workflowTransferPOJO);
                } else {
                    title = workflowHelp.getTitleValue(titles, formExplainMap, workOrderFormExplainMap, workflowTransferPOJO, workflowNodeDataMap, 50);
                }

                workflowTaskNodeEntity.setTitle(title);

                workflowTaskNodeModel.insert(workflowTaskNodeEntity);
                workflowNodeId = workflowTaskNodeEntity.getId();
                log.info("create task success taskNodeId --------------" + workflowTaskNodeEntity.getId());
            }
        } catch (XbbException e) {
            log.error("com.xbongbong.workflow.service.strategy.node.impl.WorkflowNodeApproveStrategy.createTask fail", e);
            throw new WorkflowException(e.getMsg());
        }
        WorkflowCreateTaskNodePojo workflowCreateTaskNodePojo = new WorkflowCreateTaskNodePojo();
        workflowCreateTaskNodePojo.setIsNeedApproval(true);
        workflowCreateTaskNodePojo.setIsWhitoutApproval(false);
        workflowCreateTaskNodePojo.setTaskId(workflowTransferPOJO.getTaskId());
        workflowCreateTaskNodePojo.setWorkflowNodeId(workflowNodeId);
        return workflowCreateTaskNodePojo;
    }

    
    @Override
    public void after(WorkflowTransferPOJO workflowTransferPOJO, WorkflowNodeEntity workflowNodeEntity) {
        super.after(workflowTransferPOJO, workflowNodeEntity);
    }
    
    @Override
    public void check() {
        super.check();
    }
    
    @Override
    public WorkflowNoApproverBo createTaskNode(WorkflowTransferPOJO workflowTransferPOJO, WorkflowNodeEntity nodeEntity, Long lastNodeId) throws WorkflowException {
        // 是否自动通过
        WorkflowNoApproverBo workflowNoApproverBo = new WorkflowNoApproverBo();
        Integer autoPaas = 0;
        ApprovalNode approvalNode = JSON.parseObject(nodeEntity.getConfigData(), ApprovalNode.class);
        // 负责人处理
        List<OptionalRangeEntity> mainUser = approvalNode.getMainUserList();
        if (Objects.nonNull(mainUser) && !mainUser.isEmpty()) {
            // 获取节点人员
            Set<String> nodeTaskUserList = getNodeTaskUserList(mainUser, workflowTransferPOJO);
            if (!nodeTaskUserList.isEmpty()) {
                // 审批人去重，如果是或签，其他节点要自动通过
                WorkflowEntity workflowEntity = workflowModel.getByKey(nodeEntity.getWorkflowId(), nodeEntity.getCorpid());

                Map<String, Object> param = new HashMap<>();
                param.put(ParameterConstant.CORPID, nodeEntity.getCorpid());
                param.put(ParameterConstant.APPID, nodeEntity.getAppId());
                param.put(ParameterConstant.MENUID, nodeEntity.getMenuId());
                param.put(ParameterConstant.FORMID, nodeEntity.getFormId());
                param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                param.put("taskId", workflowTransferPOJO.getTaskId());
                param.put(ParameterConstant.ORDER_BY_STR, "update_time asc, id asc");
                List<WorkflowTaskNodeEntity> workflowTaskNodeEntities = workflowTaskNodeModel.findEntities(param);

                // 当前审批发起人节点
                WorkflowTaskNodeEntity createTaskNode = new WorkflowTaskNodeEntity();
                for (WorkflowTaskNodeEntity workflowTaskNodeEntity : workflowTaskNodeEntities) {
                    if (isCreateTaskNode(workflowTaskNodeEntity)) {
                        // 这里的任务是重新提交的开始节点,要查到最新的
                        createTaskNode = workflowTaskNodeEntity;
                    }
                }

                Set<String> beforeUsers = new HashSet<>();
                LinkedHashMap<Long, Set<String>> taskNodeUsers = new LinkedHashMap<>();
                for (WorkflowTaskNodeEntity workflowTaskNodeEntity : workflowTaskNodeEntities) {
                    if (isApprovalNode(workflowTaskNodeEntity)) {
                        if (createTaskNode.getAddTime() != null && createTaskNode.getAddTime() <= workflowTaskNodeEntity.getAddTime()) {
                            if (!Objects.equals(workflowTaskNodeEntity.getLastNodeId(), 0L)) {
                                beforeUsers.add(workflowTaskNodeEntity.getUserId());
                                taskNodeUsers.computeIfAbsent(workflowTaskNodeEntity.getWorkflowNodeId(), t -> new HashSet<>()).add(workflowTaskNodeEntity.getUserId());
                            }
                        }
                    }
                }

                // 审批人去重
                Integer approverDedup = workflowEntity.getApproverDedup();
                // 发起人是审批人时是否通过
                Integer autoApprovedPass = workflowEntity.getAutoApprovedPass();
                if (Objects.equals(approvalNode.getSignType(), SignTypeEnum.ORSIGN.getValue())) {
                    // 或签
                    if (Objects.equals(autoApprovedPass, BasicConstant.ONE)) {
                        // 发起人是审批人时通过
                        if (nodeTaskUserList.contains(createTaskNode.getUserId())) {
                            nodeTaskUserList.remove(createTaskNode.getUserId());
                            // 生成或签通过节点
                            createApprovalNode(nodeTaskUserList, workflowTransferPOJO, nodeEntity, lastNodeId, TaskTypeEnum.OTHER_COMMIT);
                            // 生成或签系统通过节点
                            createApprovalNode(Collections.singletonList(createTaskNode.getUserId()), workflowTransferPOJO, nodeEntity, lastNodeId, TaskTypeEnum.SYSTEM_PASS);
                            autoPaas = 1;
                        } else {
                            WorkflowDeDuplicationBo workflowDeDuplicationBo = deDuplicationOfApprovers(approverDedup, nodeTaskUserList, beforeUsers, taskNodeUsers, lastNodeId);

                            if (workflowDeDuplicationBo.getFlag()) {
                                createApprovalNode(workflowDeDuplicationBo.getApproverDedupIds(), workflowTransferPOJO, nodeEntity, lastNodeId, TaskTypeEnum.SYSTEM_PASS);
                                createApprovalNode(workflowDeDuplicationBo.getNodeTaskUserList(), workflowTransferPOJO, nodeEntity, lastNodeId, TaskTypeEnum.OTHER_COMMIT);
                                autoPaas = 1;
                            } else {
                                createApprovalNode(nodeTaskUserList, workflowTransferPOJO, nodeEntity, lastNodeId, TaskTypeEnum.UNTREATED);
                            }
                        }
                    } else {
                        WorkflowDeDuplicationBo workflowDeDuplicationBo = deDuplicationOfApprovers(approverDedup, nodeTaskUserList, beforeUsers, taskNodeUsers, lastNodeId);

                        if (workflowDeDuplicationBo.getFlag()) {
                            createApprovalNode(workflowDeDuplicationBo.getApproverDedupIds(), workflowTransferPOJO, nodeEntity, lastNodeId, TaskTypeEnum.SYSTEM_PASS);
                            createApprovalNode(workflowDeDuplicationBo.getNodeTaskUserList(), workflowTransferPOJO, nodeEntity, lastNodeId, TaskTypeEnum.OTHER_COMMIT);
                            autoPaas = 1;
                        } else {
                            createApprovalNode(nodeTaskUserList, workflowTransferPOJO, nodeEntity, lastNodeId, TaskTypeEnum.UNTREATED);
                        }
                    }

                } else if (Objects.equals(approvalNode.getSignType(), SignTypeEnum.COUNTERSIGN.getValue())) {
                    // 会签
                    if (Objects.equals(autoApprovedPass, BasicConstant.ONE)) {
                        // 发起人是审批人时通过
                        if (nodeTaskUserList.contains(createTaskNode.getUserId())) {
                            nodeTaskUserList.remove(createTaskNode.getUserId());
                            // 生成会签待处理节点
                            createApprovalNode(nodeTaskUserList, workflowTransferPOJO, nodeEntity, lastNodeId, TaskTypeEnum.UNTREATED);
                            // 生成会签系统通过节点
                            createApprovalNode(Collections.singletonList(createTaskNode.getUserId()), workflowTransferPOJO, nodeEntity, lastNodeId, TaskTypeEnum.SYSTEM_PASS);
                            if (CollectionsUtil.isEmpty(nodeTaskUserList)) {
                                autoPaas = 1;
                            }
                        } else {
                            WorkflowDeDuplicationBo workflowDeDuplicationBo = deDuplicationOfApprovers(approverDedup, nodeTaskUserList, beforeUsers, taskNodeUsers, lastNodeId);

                            if (workflowDeDuplicationBo.getFlag()) {
                                createApprovalNode(workflowDeDuplicationBo.getApproverDedupIds(), workflowTransferPOJO, nodeEntity, lastNodeId, TaskTypeEnum.SYSTEM_PASS);
                                if (CollectionsUtil.isEmpty(workflowDeDuplicationBo.getNodeTaskUserList())) {
                                    autoPaas = 1;
                                } else {
                                    createApprovalNode(workflowDeDuplicationBo.getNodeTaskUserList(), workflowTransferPOJO, nodeEntity, lastNodeId, TaskTypeEnum.UNTREATED);
                                }
                            } else {
                                createApprovalNode(nodeTaskUserList, workflowTransferPOJO, nodeEntity, lastNodeId, TaskTypeEnum.UNTREATED);
                            }
                        }
                    } else {
                        WorkflowDeDuplicationBo workflowDeDuplicationBo = deDuplicationOfApprovers(approverDedup, nodeTaskUserList, beforeUsers, taskNodeUsers, lastNodeId);

                        if (workflowDeDuplicationBo.getFlag()) {
                            createApprovalNode(workflowDeDuplicationBo.getApproverDedupIds(), workflowTransferPOJO, nodeEntity, lastNodeId, TaskTypeEnum.SYSTEM_PASS);
                            if (CollectionsUtil.isEmpty(workflowDeDuplicationBo.getNodeTaskUserList())) {
                                autoPaas = 1;
                            } else {
                                createApprovalNode(workflowDeDuplicationBo.getNodeTaskUserList(), workflowTransferPOJO, nodeEntity, lastNodeId, TaskTypeEnum.UNTREATED);
                            }
                        } else {
                            createApprovalNode(nodeTaskUserList, workflowTransferPOJO, nodeEntity, lastNodeId, TaskTypeEnum.UNTREATED);
                        }
                    }

                }

            } else {
                // 审批人为空时
                workflowNoApproverBo = noApproverHandle(workflowTransferPOJO, nodeEntity, lastNodeId);
                autoPaas = workflowNoApproverBo.getAutoPaas();
            }

        }

        // 抄送人处理
        Integer enableCcFlag = approvalNode.getEnableCcFlag();
        if (Objects.equals(enableCcFlag, 1)) {
            List<OptionalRangeEntity> ccUser = approvalNode.getCcUserList();
            if (Objects.nonNull(ccUser) && !ccUser.isEmpty()) {
                // 获取节点人员
                Set<String> nodeTaskUserList = getNodeTaskUserList(ccUser, workflowTransferPOJO);
                if (Objects.equals(autoPaas, 1)) {
                    createApprovalNode(nodeTaskUserList, workflowTransferPOJO, nodeEntity, lastNodeId, TaskTypeEnum.CC);
                } else {
                    createApprovalNode(nodeTaskUserList, workflowTransferPOJO, nodeEntity, lastNodeId, TaskTypeEnum.WAIT_CC);
                }
            }
        }

        workflowNoApproverBo.setAutoPaas(autoPaas);
        return workflowNoApproverBo;
    }


    /**
     * Description: 处理审批人去重逻辑
     * @param approverDedup 审批人去重设置
	 * @param nodeTaskUserList 当前节点的人id
	 * @param beforeUsers 之前所有审批节点的人id
	 * @param taskNodeUsers 之前审批节点id和相应审批人id
	 * @param lastNodeId 上一个节点id
     * @return com.xbongbong.workflow.pojo.bo.WorkflowDeDuplicationBo
     * @throws
     * @author 魏荣杰
     * @date 2021/8/26 15:16
     * @since
     */
    private WorkflowDeDuplicationBo deDuplicationOfApprovers(Integer approverDedup, Set<String> nodeTaskUserList, Set<String> beforeUsers, LinkedHashMap<Long, Set<String>> taskNodeUsers, Long lastNodeId) {
        WorkflowDeDuplicationBo workflowDeDuplicationBo = new WorkflowDeDuplicationBo();
        boolean flag = false;
        Set<String> approverDedupIds = new HashSet<>();
        if (Objects.equals(approverDedup, ApproverDeduplicationEnum.SAVE_FIRST_APPROVER.getFlag())) {
            // 同一个审批人在流程中出现多次时，仅保留第一个
            Iterator<String> iterator = nodeTaskUserList.iterator();
            while (iterator.hasNext()) {
                String v = iterator.next();
                if (beforeUsers.contains(v)) {
                    iterator.remove();
                    approverDedupIds.add(v);
                    flag = true;
                }
            }
        } else if (Objects.equals(approverDedup, ApproverDeduplicationEnum.APPROVERS_CONTINUOUSLY_DEDUPLICATION.getFlag())) {
            // 同一个审批人仅在连续出现时，自动去重
            Set<String> lastNodeUsers = new HashSet<>();
            Iterator<Map.Entry<Long, Set<String>>> entryIterator = taskNodeUsers.entrySet().iterator();
            while (entryIterator.hasNext()) {
                lastNodeUsers = entryIterator.next().getValue();
            }
            Iterator<String> iterator = nodeTaskUserList.iterator();
            while (iterator.hasNext()) {
                String v = iterator.next();
                if (Objects.nonNull(lastNodeUsers) && lastNodeUsers.contains(v)) {
                    iterator.remove();
                    approverDedupIds.add(v);
                    flag = true;
                }
            }
        } else {
            // 不启用自动去重

        }

        workflowDeDuplicationBo.setFlag(flag);
        workflowDeDuplicationBo.setApproverDedupIds(approverDedupIds);
        workflowDeDuplicationBo.setNodeTaskUserList(nodeTaskUserList);
        return workflowDeDuplicationBo;
    }


    @Override
    public void logger(WorkflowTransferPOJO workflowTransferPOJO, WorkflowNodeEntity nodeEntity, WorkflowTaskLogStatusEnum workflowTaskLogStatusEnum, WorkflowException workflowException) {
        super.logger(workflowTransferPOJO, nodeEntity, workflowTaskLogStatusEnum, workflowException);
    }


}
